<style scoped>
@import url(./css/ldtable.css);
.page_con {
  padding:0 0;
}
/*文本溢出出现省略号*/
.text_overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.text_center{
  text-align: center;
}
/* .ldht_table   .el-table td {
    color: #333 !important;
    font-weight: 400!important;
    font-size:12px!important;
    line-height: 42px!important;
  }
  .ldht_table   table{
    width: 100%!important;
  }
  .ldht_table   .el-pager li,   .ldht_table   .btn-next,  .ldht_table    .btn-prev,  .ldht_table    .el-pager li{
    font-size:16px!important;
    border: none!important;
    background: transparent!important;
    color: #333!important;
    font-weight: normal!important;
  }
  .ldht_table   .el-pagination.is-background .el-pager li:not(.disabled).active{
    background-color: transparent!important;
    color: #5094F5!important;
  }
  .ldht_table   .btn-prev .el-icon,  .ldht_table   .btn-next .el-icon {
      font-size: 18px!important;
  }
  .ldht_table   .el-table th>.cell{
      font-weight: 400!important;
      font-size: 12px!important;
      background: #EBEFFB!important;
      margin-bottom:5px!important;
      color:#333!important;
     
  }
  .ldht_table    .el-table--border th.is-leaf{
    color:#333!important;
  }
  .ldht_table   .el-table .el-table__body .cell{
    background: rgba(235, 239, 251,.5);
    margin-bottom:5px!important;
  }
 
  .ldht_table   .el-table .cell{
   line-height: 32px!important;
}
.ldht_table   .el-table .cell{
  padding: 0 !important;
} */

</style>
<template>
  <div :class="tableClass" :style="{height: tableHeight}" >
    <el-table
      id="myTable"
      ref="myTable"
      :data="tableData"
      :stripe="isStripe"
      :border="isBorder"
      style="width:100%"
      :height="tableHeight"
      align="center"
      @row-click="rowClick"
      @cell-click="cellClick"
      @cell-dblclick="cellDBClick"
      @selection-change="selectionChange"
    >
      <!-- <el-table-column align="center" type="index" width="80" label="序号" v-if="showIndex">
        <template slot-scope="scope">
          <span>{{(pageData.pageIndex - 1) * pageData.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column> -->
      <!-- <el-checkbox-group v-model="checkedItems"  @change="handleCheckedItemsChange"> -->
      <el-table-column
        v-for="(item,i) in columns"
        :key="i"
        :type="(item.type||'')"
        :prop="(item.field||'')"
        :label="item.title"
        :width="((item.type=='index'||item.type=='checkbox')?(item.width||60):(item.width||'auto'))"
        :align="(item.align||'center')"
        :labelClassName="item.thClass"
        :formatter="item.formatter"
      >
        <!-- <template slot-scope="scope" v-if="(item.type && item.type == 'index')">
          <span>{{(pageData.pageIndex - 1) * pageData.pageSize + scope.$index + 1}}</span>
        </template> -->
        <template slot="header" slot-scope="scope">
          <el-checkbox  v-if="item.type=='checkbox'" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
          <span v-else>{{ item.title }}</span>
        </template>
        <template slot-scope="scope" >
          <p    :class="['text_overflow',item.tdClass,,fitColors[scope.$index]]" v-if="item.type=='date'">{{ scope.row[item.field]?dateFormat(scope.row[item.field]):'' }}</p>
          <span :class="['text_overflow',indexClass(scope.$index,item.tdClass),fitColors[scope.$index]]" v-else-if="item.type=='index'">{{(pageData.pageIndex - 1) * pageData.pageSize + scope.$index + 1}}</span>
          <p    :class="['text_overflow',indexClass(scope.$index,item.tdClass),fitColors[scope.$index]]" v-else-if="item.type=='checkbox'">
            <el-checkbox :label="i" :key="i" ref="ckItem" @change="handleCkItemChange(i)"></el-checkbox>
          </p>
          <p    :class="['text_overflow',(dataFieldClass(scope.row[item.field],item.tdClass)),fitColors[scope.$index]]" :title="(item.datas?(item.datas[scope.row[item.field]]):scope.row[item.field])" v-else>{{ item.datas?(item.datas[scope.row[item.field]]):scope.row[item.field] }}</p>
        </template>
      </el-table-column>
      <!-- </el-checkbox-group> -->
    </el-table>
    <div class="text_center page_con" v-if="showPage">
      <el-pagination
        background
        :layout="pageLayout"
        :page-size="pageData.pageSize"
        :total="pageData.total"
        @current-change="changePage"
      ></el-pagination>
    </div>
  </div>
  <!-- <table v-else :ref="scrollTable" :class="tableClass" :style="{height: tableHeight}"></table> -->
</template>
<script>
/**
 * 默认表格居中显示，若哪一列不居中，设置align: left/right/center
 * params 中不要传分页参数
 * pageSize可不传,默认10
 */
// import EventBus from "@/lib/EventBus.js"; //bus事件总线
import { dateFormat } from "./lib/common";
export default {
  name: "myTable",
  props: {
    tableClass: {
      type: Array | String,
      default: () => {
        return "";
      },
    },
    tableHeight: {//设置高度，表头固定
      type: Number | String,
      default: () => {
        return "auto";
      },
    },
    showIndex:{
      type: Boolean,
      default: true,
    },
    columns: Array, //表头配置
    url: String, //请求地址
    params: Object, //请求参数
    pageSize: Number, //分页数据
    cellClickParams: Object, //单元格点击事件
    cellClickRes: Object,
    isStripe: {
      type: Boolean,
      default: false,
    },
    isBorder:{
      type: Boolean,
      default: false,
    },
    datas: Array,
    pageLayout: {
      type: String,
      default: "prev, pager, next",
    },
    isAutoScroll:{
      type: Boolean,
      default: false,
    }
  },
  computed: {
    showPage() {
       return (!this.datas.length>0 || (this.tableHeight=='auto'&&(this.datas&&this.datas.length>this.pageData.pageSize)))
    },
    fitColors(){
      let arr = [];
      if(this.datas){
        this.datas.map(item=>{
          let fitCol = this.columns.filter(item=>item.colorFit)[0];
          if(fitCol){
            arr.push(this.dataFieldClass(item[fitCol.field],fitCol.tdClass))
          }else{
            arr.push("")
          }
          
        })
      }
      return arr;

    }
  },
  data() {
    return {
      result:"data.data",
      pageData: {
        pageSize:10,
        total: 0,
        pageIndex: 1,
      },
      tableData: [],
      autoScrollTimer:null,
      checkAll: false,//是否全选
      checkedItems: [],//选中数组（下标）
      checkedItemDatas: [],//选中数组（数据）
      isIndeterminate: true//控制全选样式
    };
  },
  methods: {
    dateFormat(dateStr){
      return dateFormat(dateStr)
    },
    indexClass(index,classData){
      if(typeof classData == 'string'){
        return classData;
      }else if(typeof classData == 'object'){
        return classData[index] || '';
      }
    },
    dataFieldClass(value,classData,fit){
      let className = ""
      if(typeof classData == 'string'){
        className = classData;
      }else if(typeof classData == 'object'){
        className = classData[value] || '';
      }
      return className;
    },
    getData(pageIndex) {
       console.log(pageIndex,"this.pageData.pageSize",this.pageData.pageSize)
      //表格数据获取
      axios({
        url: this.url,
        method: "post",
        params: Object.assign(this.params||{}, {
          pageIndex: pageIndex,
          pageSize: this.pageData.pageSize,
        }),
      }).then((res) => {
        var data = res.data;
        console.log(res,"res",data)
        this.tableData =data.data;
        this.pageData.total = data.total;
      });
    },
    getResult(res){
         var result=this.result
            var obj=result.split(".")
            var res_=res
              obj.forEach(item => {
                  res_=res_[item]
              });
            return res_
    },
    getStaticData(pageIndex){
      this.tableData = this.datas.slice(pageIndex*this.pageData.pageSize,(pageIndex+1)*this.pageData.pageSize);
    },
    changePage(page) {
      //页码改变
      this.pageData.pageIndex = page;
      if(this.datas.length>0){
        this.getStaticData(page - 1)
      }else{
        this.getData(page - 1); //从0开始
      }
      
    },
    rowClick(row, column, event) {
      //单击行
      //row 选中行的数据
      // console.log(row, column, event)
      if (this.cellClickRes) {
        this.cellClickRes(row);
      }
    },
    cellClick(row, column, cell, event) {
      console.log(column.property,row)
      //单击单元格
      if (this.cellClickParams && this.cellClickParams[column.property]) {
        console.log(column.property, this.cellClickParams[column.property]);
      }
      this.EventBus.$emit("handleTableClick", {
        field: column.property,
        clickEvent:1,
        data: row,
      });
    },
    cell() {
      return this.row;
    },
    cellDBClick(row, column, cell, event) {
      //双击单元格
      //column.label 选中单元格的列名
      //column.property 字段名
      // console.log(row, column, cell, event)
    },
    handleCkItemChange(i){
      console.log(i)
    },
    selectionChange(selection){
      this.EventBus.$emit("handleTableSelect", selection);
    },
    autoScroll(){//自动滚动
      let parent = this.$refs['myTable'].bodyWrapper.children[0].children[1];
      let first=this.$refs['myTable'].bodyWrapper.children[0].children[1].children;
      let second=this.$refs['myTable'].bodyWrapper.children[0].children[1].children[1];
      this.$refs['myTable'].bodyWrapper.children[0].children[1].scrollTop = (100)
      // this.autoScrollTimer = setInterval(this.scrollOneData,2500)
    },
    scrollOneData(){
      this.tableData.push(this.tableData[0]);//把第一条数据插入数组最有一条
      this.tableData.shift();//删除数组中第一条数据
      // this.$forceUpdate();
      // var parent = document.getElementById('con1');
      // var first = document.getElementById('el-table__body-wrapper').children[0];
      // var second = document.getElementById('el-table__body-wrapper').children[1];
      // parent.removeChild(first);
      // parent.removeChild(second);
      // parent.appendChild(first);
      // parent.appendChild(second);
    },
    handleCheckAllChange(val) {//全选/全不选
      this.checkedItems = val ? this.tableData.map((item,i)=>i) : [];
      this.isIndeterminate = false;
      this.checkedItems.map(item=>{
        this.checkedItemDatas.push(this.tableData[item]);
      })
      console.log('选中数据:',this.checkedItemDatas)
    },
    handleCheckedItemsChange(value) {//单项选中
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tableData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
      this.checkedItemDatas = [];
      this.checkedItems.map(item=>{
        this.checkedItemDatas.push(this.tableData[item]);
      })
      console.log('选中数据:',this.checkedItemDatas)
    },

  },
  watch:{
    datas:{
      handler(val){
        if(val){
          this.getStaticData(0)
          this.pageData.total = this.datas.length;
        }
      },
      deep:true
    }
  },
  mounted() {
    this.pageData.pageSize = this.pageSize || this.pageData.pageSize;
    console.log(this.datas,"this.datas")
    if (this.datas.length>0) {
      this.getStaticData(0)
      this.pageData.total = this.datas.length;
      if(this.isAutoScroll){
        this.autoScroll();
      }
    } else {
      this.getData(0);
    }
  },
  beforeDestroy(){
    clearInterval(this.autoScrollTimer)
  }
};
</script>
